package ch.unisi.inf.java.project.riskbami.view;

import ch.unisi.inf.java.project.riskbami.model.*;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import javax.imageio.*;
import java.util.List;
import javax.swing.border.EtchedBorder;
import javax.swing.border.EmptyBorder;

/**
 * This class handles the main frame of the game.
 * 
 * @author minellir@lu.unisi.ch
 * @author babazadm@lu.unisi.ch
 */
public final class RiskFrame extends JFrame implements GameListener, PlayerListener, CountryListener{

    private final static int ERR_ATTACK = 0;
    private final static int ERR_FORTIFY = 1;
    private final static int ERR_TRADE = 2;
    private final static int OK_TRADE = 3;
    private final static int GAME_FINISHED = 4;
    private final static int SLIDE_FORTIFY = 5;
    private final static int SLIDE_ATTACK = 6;

    private final Game game;
    private final ImageIcon map;
    private final Raster pixelMatrix;
    private HashMap<Color, String> colorsToCountry;
    private final RiskFrame frame = this;
    private BufferedImage bufferedMap, bufferedColoredMap, bufferedSeaBackground;
    private final JLabel mapPanel;
    private JButton cardsButton, attackButton, fortifyButton, passButton;
    private Country selCountry1, selCountry2;
    private final Graphics2D writableMap;
    private boolean firstClick = true;
    private JTextArea text;
    
    public RiskFrame(final Game game, final ImageIcon map, final Raster pixelMatrix, final HashMap<Color, String> colorsToCountry, final BufferedImage bufferedMap) {
        this.game = game;
        game.addGameListener(this);
        for(final Player p : game.getPlayers()){
            p.addPlayerListener(this);
        }
        this.map = map;
        this.pixelMatrix = pixelMatrix;
        this.colorsToCountry = colorsToCountry;
        this.bufferedMap = bufferedMap;
        this.bufferedColoredMap = new BufferedImage(bufferedMap.getWidth(), bufferedMap.getHeight(), bufferedMap.getType());
        try{
            this.bufferedSeaBackground = ImageIO.read(getClass().getResource("images/sea.jpg"));
        } catch(IOException ex){};
        
        this.writableMap = bufferedColoredMap.createGraphics();
        
        Font font = writableMap.getFont().deriveFont(20f);
        writableMap.setFont(font);
        writableMap.setPaint(new Color(1,1,1));
        
        setCountriesFromFile();
        computeCountriesFromMap();
        game.randomCountryDistributor();
        
        for(Country c : game.getCountries()){
            c.addCountryListener(this);
        }
        
        game.createDeck();
        game.shuffleDeck();
        
        createPlayerColoringMap();
             
        this.mapPanel = new JLabel(new ImageIcon (bufferedColoredMap));

        createGameFrame(); 
        frame.setResizable(false);
        updateStatus();
        playerChanged();
        
        mapPanel.addMouseListener(new MouseAdapter() {
            public void mouseClicked(final MouseEvent ev) {
                Country clicked = clickedCountry(ev.getX(), ev.getY());
                if(clicked == null){
                    text.append(game.getCurrentPlayer()+" click on the sea... \n");
                } else {
                    text.append(game.getCurrentPlayer()+" click on "+ clicked + "...\n");
                }
                final int phase = game.getTurnPhase();
                if(clicked!=null){
                    if(phase == 1){
                        PlaceArmiesCommand place = new PlaceArmiesCommand(game, clicked, 1);
                            if(place.canExecute()){
                                place.execute();
                                text.append("Remaining armies for "+game.getCurrentPlayer()+" --> "+ game.getCurrentPlayer().getPerTurnArmies()+"\n");
                            }
                        } else if(firstClick){
                            if(selCountry1 != null){
                                repaintCountry(selCountry1, game.getOwnerOf(selCountry1).getColor());
                            }
                            selCountry1 = clicked;
                            repaintCountry(clicked, alterateColor(game.getOwnerOf(clicked).getColor()));
                            setFirstClick(false);
                        } else if(selCountry1 != clicked && clicked.getNearbyCountries().contains(selCountry1)){
                            if(selCountry2 != null){
                                repaintCountry(selCountry2, game.getOwnerOf(selCountry2).getColor());
                            }
                            selCountry2 = clicked;
                            repaintCountry(clicked, alterateColor(game.getOwnerOf(clicked).getColor()));
                            setFirstClick(true);
                        } else {
                            if(selCountry1 != null){
                                repaintCountry(selCountry1, game.getOwnerOf(selCountry1).getColor());
                            }
                            selCountry1 = clicked;
                            repaintCountry(clicked, alterateColor(game.getOwnerOf(clicked).getColor()));
                            if(selCountry2 != null){
                                repaintCountry(selCountry2, game.getOwnerOf(selCountry2).getColor());
                                selCountry2 = null;
                            }
                        }
                     } else {
                         if(selCountry1 != null){
                            repaintCountry(selCountry1, game.getOwnerOf(selCountry1).getColor());
                            selCountry1 = null;
                        }
                        if(selCountry2 != null){
                            repaintCountry(selCountry2, game.getOwnerOf(selCountry2).getColor());
                            selCountry2 = null;
                        }
                     }
                }
            }); 
        }   
    
    private final Color alterateColor(final Color c){
        int oldRGB = c.getRGB(); 
        return new Color(oldRGB - (oldRGB/3));
    }
    
    private final int[] getNumberOfArmiesCoordinates(Country country){
        int[] point = new int[] {0,0};
        for(int y = 0; y < bufferedColoredMap.getHeight(); y++) {
            for(int x = 0; x < bufferedColoredMap.getWidth(); x++) {
                Color actualColor = new Color (pixelMatrix.getSample(x, y, 0), 
                                        pixelMatrix.getSample(x, y, 1), 
                                        pixelMatrix.getSample(x, y, 2));
                if(actualColor.equals(Color.WHITE)){
                    ArrayList<Color> neighborsPixels = getNearbyPixels(x, y);
                    Color countryColor = getColorFromCountry(country);
                    if(neighborsPixels.contains(countryColor)){
                        point[0] = x;
                        point[1] = y;
                    }
                }
            }
        }
        return point;
    }
    
    private final void createPlayerColoringMap(){
        for(int y = 0; y < bufferedColoredMap.getHeight(); y++) {
            for(int x = 0; x < bufferedColoredMap.getWidth(); x++) {
                Color actualColor = new Color (pixelMatrix.getSample(x, y, 0), 
                                        pixelMatrix.getSample(x, y, 1), 
                                        pixelMatrix.getSample(x, y, 2));
                                        
                Country actualCountry = getCountryFromColor(actualColor);
                
                if(actualCountry != null && !actualColor.equals(Color.BLACK)){
                    int ownerRGB = game.getOwnerOf(actualCountry).getColor().getRGB();
                    
                    Color edgeColor = edge(x, y);
                    
                    if(edgeColor == null){
                        //It means that we're not close to an inner border, so we set RGB to owner's color
                        bufferedColoredMap.setRGB(x, y, ownerRGB);
                    } else{
                        //It means that we're close to an inner border, so we set RGB to black
                        bufferedColoredMap.setRGB(x, y, edgeColor.getRGB());
                    }
                } else if(actualColor.equals(Color.BLACK)){
                    //Used to set the background as a sea image
                    bufferedColoredMap.setRGB(x, y, bufferedSeaBackground.getRGB(x,y));
                }
                //Used to create external border of the map
                if(bufferedMap.getRGB(x,y) != Color.BLACK.getRGB() && getNearbyPixels(x,y).contains(Color.BLACK)){
                    try{
                        bufferedColoredMap.setRGB(x,y,Color.BLACK.getRGB());
                        bufferedColoredMap.setRGB(x-1,y,Color.BLACK.getRGB());
                        bufferedColoredMap.setRGB(x-1,y-1,Color.BLACK.getRGB());
                        bufferedColoredMap.setRGB(x,y-1,Color.BLACK.getRGB());
                    } catch (ArrayIndexOutOfBoundsException ex){
                        bufferedColoredMap.setRGB(x,y,Color.BLACK.getRGB());
                    }
                }
            }
        }    
    }
    
    //-- Start from the code from ImageViewer-Final 
    //-- @author Michael Kolling and David J Barnes 
    //-- Edited to be useful by Roberto Minelli
     
    /**
     * Return black if the average of the current pixel and its neighbors is white (it means
     * that all pixels has the same color), null otherwise.
     * @param xpos The x position of the pixel.
     * @param ypos The y position of the pixel.
     * @return The edge color (either black or null)
     */
    private final Color edge(final int xpos, final int ypos)
    {
        List<Color> pixels = new ArrayList<Color>(9);
        
        for(int y = ypos-1; y <= ypos+1; y++) {
            for(int x = xpos-1; x <= xpos+1; x++) {
                if( x >= 0 && x < bufferedColoredMap.getWidth() && y >= 0 && y < bufferedColoredMap.getHeight()) {
                    Color color = new Color (pixelMatrix.getSample(x, y, 0), 
                                        pixelMatrix.getSample(x, y, 1), 
                                        pixelMatrix.getSample(x, y, 2));
                    if(!color.equals(Color.WHITE) && !color.equals(Color.BLACK)){
                        pixels.add(color);
                    }
                }
            }
        }
        Color edgeColor = new Color(255 - diffRed(pixels), 255 - diffGreen(pixels), 255 - diffBlue(pixels));
        if (edgeColor.equals(Color.WHITE)){
            return null;
        }else return Color.BLACK;
    }

    /**
     * @param pixels The list of pixels to be averaged.
     * @return The average of all the red values in the given list of pixels.
     */
    private final int diffRed(final List<Color> pixels)
    {
        int max = 0;
        int min = 255;
        for(Color color : pixels) {
            int val = color.getRed();
            if(val > max) {
                max = val;
            }
            if(val < min) {
                min = val;
            }
        }
        int difference = max - min - 20;
        if(difference < 0) {
            difference = 0;
        }
        return difference;
    }

    /**
     * @param pixels The list of pixels to be averaged.
     * @return The average of all the green values in the given list of pixels.
     */
    private final int diffGreen(final List<Color> pixels)
    {
        int max = 0;
        int min = 255;
        for(Color color : pixels) {
            int val = color.getGreen();
            if(val > max) {
                max = val;
            }
            if(val < min) {
                min = val;
            }
        }
        int difference = max - min - 20;
        if(difference < 0) {
            difference = 0;
        }
        return difference;
    }

    /**
     * @param pixels The list of pixels to be averaged.
     * @return The average of all the blue values in the given list of pixels.
     */
    private final int diffBlue(final List<Color> pixels)
    {
        int max = 0;
        int min = 255;
        for(Color color : pixels) {
            int val = color.getBlue();
            if(val > max) {
                max = val;
            }
            if(val < min) {
                min = val;
            }
        }
        int difference = max - min - 20;
        if(difference < 0) {
            difference = 0;
        }
        return difference;
    }

    //--end of the ImageViewer-final code
    
    private final void updateStatus(){
        int phase = game.getTurnPhase();
        if(phase == 0 || phase == 1){
            cardsButton.setEnabled(true);
            attackButton.setEnabled(false);
            fortifyButton.setEnabled(false);
            passButton.setEnabled(false);
        } else if(phase == 2 || phase == 3){
            cardsButton.setEnabled(true);
            attackButton.setEnabled(true);
            fortifyButton.setEnabled(true);
            passButton.setEnabled(true);
        }
    }
    
     private final void createGameFrame() {

        // create command objects
        final AboutCommand aboutCommand = new AboutCommand();
        final NewGameCommand newGameCommand = new NewGameCommand();
        final QuitCommand quitCommand = new QuitCommand();

        // create menu
        final JMenuBar menuBar = new JMenuBar();
        final JMenu fileMenu = new JMenu("File");
        fileMenu.add(newGameCommand);
        fileMenu.add(quitCommand);
        menuBar.add(fileMenu);
        final JMenu aboutMenu = new JMenu("About");
        aboutMenu.add(aboutCommand);
        menuBar.add(aboutMenu);
        setJMenuBar(menuBar);
        
        setLayout(new BorderLayout());
        
        //Container for the buttons and the map
        Container contentPane = this.getContentPane();
        contentPane.setLayout(new BorderLayout());
        
        contentPane.add(mapPanel, BorderLayout.CENTER);
        
        //Toolbar for the buttons
        JPanel toolbar = new JPanel();
        toolbar.setLayout(new BorderLayout());
        
        JPanel buttonPanel = new JPanel(new GridLayout(4,0));
        buttonPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        
        //Buttons and actions
        cardsButton = new JButton("Show/Use Cards");
        buttonPanel.add(cardsButton);
        cardsButton.addActionListener(new ShowCardsListener(game));
        attackButton = new JButton("Attack!");
        buttonPanel.add(attackButton);
        attackButton.addActionListener(new AttackListener(game));
        fortifyButton = new JButton("Fortify");
        buttonPanel.add(fortifyButton);
        fortifyButton.addActionListener(new FortifyListener(game));
        passButton = new JButton("Pass");
        buttonPanel.add(passButton);
        passButton.addActionListener(new PassListener(game));
        
        toolbar.add(buttonPanel, BorderLayout.EAST);
        
        final JPanel actionPanel = new JPanel(new BorderLayout());
        actionPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Combat Log"));
        text = new JTextArea("",6,23);
        text.setEditable(false);
        text.setText("Welcome to RiskBaMi...\nIn this phase you have to place your armies, each time that an armies is placed the player changes. \n");
        final JScrollPane scroll = new JScrollPane(text);
        actionPanel.add(scroll, BorderLayout.CENTER);
        toolbar.add(actionPanel);
        
        toolbar.setBorder(new EtchedBorder(EtchedBorder.LOWERED));

        //Add the buttons to the toolbar into the container
        contentPane.add(toolbar, BorderLayout.SOUTH);

        //Adjust all
        pack();
        setVisible(true);
    }
    
    /**
     * Getters
     */
    private final Raster getPixelMatrix()
    {
        return pixelMatrix;
    }
    
    public final void appendCombatLog(final String s){
        text.append(game.getCurrentPlayer()+s);
    }
    
    private final HashMap<Color, String> getColorsToCountry()
    {
        return colorsToCountry;
    }
    
    private final BufferedImage getBufferedMap()
    {
        return bufferedMap;
    }
    
    public final Game getGame()
    {
        return game;
    }
 
    /**
     * Setters
     */
    
    private final void setFirstClick(final boolean value){
        this.firstClick = value;
    }
    
    //Inner classes for some buttons
    private final class PassListener implements ActionListener{
            private final Game game;
            private PassListener(final Game game){
                this.game = game;
            }
            
            public final void actionPerformed(final ActionEvent e) {
                final PassCommand p = new PassCommand(game);
                p.execute();
                if(selCountry1 != null){
                    repaintCountry(selCountry1, game.getOwnerOf(selCountry1).getColor());
                }
                if(selCountry2 != null){
                    repaintCountry(selCountry2, game.getOwnerOf(selCountry2).getColor());
                }
            }
    }
    
    private final class ShowCardsListener implements ActionListener{
            private final Game game;
            private ShowCardsListener(final Game game){
                this.game = game;
            }
            public final void actionPerformed(final ActionEvent e) {
                ShowCards show = new ShowCards(game);
            }
    }
    
    private final class AttackListener implements ActionListener{
            private final Game game;            
            private AttackListener(final Game game){
                this.game = game;
             }
            public final void actionPerformed(final ActionEvent e) {
                AttackCommand attack = new AttackCommand(game, selCountry1, selCountry2);
                if(attack.canExecute()){
                    attack.execute();
                    if(selCountry1 != null && selCountry2 != null){
                        text.append(game.getCurrentPlayer() + ": attacks from "+selCountry1+" to "+selCountry2+"\n");
                    }
                }
            }
    }
    
    private final class FortifyListener implements ActionListener{
            private final Game game;            
            private int howMany;
            private FortifyListener(final Game game){
                this.game = game;
             }
            public final void actionPerformed(final ActionEvent e) {
                if(selCountry1.getNumberOfArmies() > 2){
                    new Slider(1, selCountry1.getNumberOfArmies() - 1, frame, selCountry1, selCountry2, SLIDE_FORTIFY);
                    selCountry1 = null;
                    selCountry2 = null;
                } else {fortifyError();}
            }
    }
    
    /**
     * clickedCountry takes the coordinates and gives back the country object.
     * null if the sea is clicked
     */
    private final Country clickedCountry(final int x, final int y){
       final int red = pixelMatrix.getSample(x,y,0);
       final int green = pixelMatrix.getSample(x,y,1);
       final int blue = pixelMatrix.getSample(x,y,2);
       final Color c = new Color(red, green, blue);
       return frame.getCountryFromColor(c);
    }
    
    /**
     * setCountriesFromFile initialize the field of the game that holds the countries
     * as the countries written on the file
     */
    private final void setCountriesFromFile(){
        final ArrayList<Country> countries =  new ArrayList<Country>();
        final ArrayList<String> countriesNames = new ArrayList<String>();
        countriesNames.addAll(colorsToCountry.values());
        //Adding all countries without neighbors
        for(final String name : countriesNames){
            countries.add(new Country(name));
        }
        game.addAllCountries(countries);
    }
    
    /**
     * computeCountriesFromMap computes all the countries using both the map and the associated file.
     * Then compute the nearby countries of each country and set the list as the actual for the game
     * 
     * METODO SUPER CAVALLINOOOO! :)
     */
    private final void computeCountriesFromMap(){
        int actualCountryIndex, nearbyCountryIndex = 0;
        Color actualColor, nearbyColor;
        Country actualCountry, nearbyCountry, countryWithNeighbor;
        final ArrayList<Country> countries = game.getCountries();
        ArrayList<Color> nearbyPixels = new ArrayList<Color>();
        
        //Get and add the neighbors
        for(int y = 0; y < pixelMatrix.getHeight(); y++) {
            for(int x = 0; x < pixelMatrix.getWidth(); x++) {
                actualColor = new Color (pixelMatrix.getSample(x, y, 0), 
                                        pixelMatrix.getSample(x, y, 1), 
                                        pixelMatrix.getSample(x, y, 2));
                                        
                actualCountry = getCountryFromColor(actualColor);
                
                if(actualCountry != null && actualColor != Color.BLACK){
                    
                    actualCountryIndex = nameToIndex(actualCountry.getName());
                    nearbyPixels = getNearbyPixels(x,y);
                    
                    for(final Color color : nearbyPixels){
                        nearbyCountry = getCountryFromColor(color);
                        //The following conditions check whether the nearby country is not null, is not equal to the actual country and whether the actual country
                        //have the nearbyCountry that we are processing just in its list of neighbors
                            if(nearbyCountry != null){
                                nearbyCountryIndex = nameToIndex(nearbyCountry.getName());
                                if(countries.get(actualCountryIndex) != countries.get(nearbyCountryIndex)){
                                    if (!countries.get(actualCountryIndex).containsNeighborsName(nearbyCountry.getName())){
                                        countryWithNeighbor = countries.get(actualCountryIndex).addNearby(countries.get(nearbyCountryIndex));
                                        countries.set(actualCountryIndex, countryWithNeighbor);
                                    }
                                    if(!countries.get(nearbyCountryIndex).containsNeighborsName(actualCountry.getName())){
                                        countryWithNeighbor = countries.get(nearbyCountryIndex).addNearby(countries.get(actualCountryIndex));
                                        countries.set(nearbyCountryIndex, countryWithNeighbor);
                                    }   
                                }
                            }
                        }
                    }
                }
            }
            game.addAllCountries(countries);
    }
    
    /**
     * getNearbyPixels return the list of all neighbors pixel of the pixel at the
     * given coordinates
     */
    private final ArrayList<Color> getNearbyPixels(final int posnx, final int posny)
    {
        final ArrayList<Color> pixels = new ArrayList<Color>();
        
        // this 2 old-style for loops are used to identify the 9 pixels (8 neighbors + itself) 
        // that are going to create the new pixel with the average of the 9.
        for(int y = posny - 1; y <= posny + 1; y ++) {
            for(int x = posnx - 1; x <= posnx + 1; x ++) {
                // I need this check to verify wheter I am near a border. In this case the pixels
                // may not be 9, in a corner, for example the pixels are only 4.
                if(x < pixelMatrix.getWidth() && y < pixelMatrix.getHeight() && x >= 0 && y >= 0){
                    Color actual = new Color (pixelMatrix.getSample(x, y, 0), 
                                            pixelMatrix.getSample(x, y, 1), 
                                            pixelMatrix.getSample(x, y, 2));                 
                    pixels.add(actual);
                }
            }
        }
        return pixels;
    }
    
    /**
     * getCountryFromColor provide to return the Country object of the given
     * color
     */
    private final Country getCountryFromColor(final Color color){
        final ArrayList<Country> countries = game.getCountries();
        Country requestedCountry = null;
        final String countryName = colorsToCountry.get(color);
        if(countryName != null){
            for(final Country c : countries){
                if(c.getName().equals(countryName)){
                    requestedCountry = c;
                }
            }
        }
        return requestedCountry;
    }
    
    /**
     * getColorFromCountry provide to return the Color object of the given
     * country
     */
    private final Color getColorFromCountry(final Country country){
        Color colorOfCountry = null;
        for(final Color c : colorsToCountry.keySet()){
            if(colorsToCountry.get(c).equals(country.getName())){
                colorOfCountry = c;
            }
         }
        return colorOfCountry;
    }
    
    /**
     * nameToIndex takes the name of a country and return the index in the arrayList of countries
     * that belongs to the actual game
     */
    private final int nameToIndex(final String countryName){
        int index = 0;
        final ArrayList<Country> countries = game.getCountries();
        for(final Country c : countries){
            if(c.getName().equals(countryName)){
                index = countries.indexOf(c);
            }
        }   
        return index;
    }

    
    //-- Listener implementation
    
    public final void phaseChanged(){
        if(game.getTurnPhase() != 0){
            text.append(game.getCurrentPlayer() + ": current phase now is " + game.getTurnPhase() + "\n");
        }
        updateStatus();
    }
    
    public final void playerChanged(){
        text.append("Now is "+game.getCurrentPlayer() + "'s turn \n");
        GetArmiesCommand getArmies = new GetArmiesCommand(game);
        if(getArmies.canExecute()){
            getArmies.execute();
        }
        game.getCurrentPlayer().playTurn();
    }
    
    private final void repaintCountry(final Country changed, final Color color){
        for(int y = 0; y < bufferedColoredMap.getHeight(); y++) {
            for(int x = 0; x < bufferedColoredMap.getWidth(); x++) {
                final Color actualColor = new Color (pixelMatrix.getSample(x, y, 0), 
                                        pixelMatrix.getSample(x, y, 1), 
                                        pixelMatrix.getSample(x, y, 2));
                                        
                Country actualCountry = getCountryFromColor(actualColor);
                
                if(actualCountry == changed && bufferedColoredMap.getRGB(x, y) != Color.BLACK.getRGB()){
                    final int colorRGB = color.getRGB(); 
                    bufferedColoredMap.setRGB(x, y, colorRGB);
                }
            }
        }
        final int[] point = getNumberOfArmiesCoordinates(changed);
        final int numArmies = changed.getNumberOfArmies();
        if(point != new int[] {0,0} && numArmies != 0){
            writableMap.drawString(""+numArmies, point[0], point[1]);
        }
    mapPanel.repaint();
    }
    
    public final void countryLost(final Player old, final Player niu){
        if(old.getOwnedCountries().size() == 0){
            game.removePlayer(old);
            niu.addOwnedCards(old.getOwnedCards());
        }
    }
    
    public final void countryConquer(final Country changed, final Player newOwner){
        repaintCountry(changed, newOwner.getColor());
        if(newOwner.getOwnedCountries().size() == game.getCountries().size()){
            game.setIsFinished();
            popUpDialog(GAME_FINISHED);
            frame.setVisible(false);                                                              
            new PreRiskFrame();
        } else if(newOwner.isHuman()){
            if(selCountry1.getNumberOfArmies() > 4){
                new Slider(Math.min(3 , selCountry1.getNumberOfArmies() - 1), selCountry1.getNumberOfArmies() - 1, frame, selCountry1, selCountry2, SLIDE_ATTACK);
            } else {
                newOwner.fortify(selCountry1, selCountry2, Math.min(3, selCountry1.getNumberOfArmies() - 1));
            }
        }
    }
    
    public final void armiesChanged(final Country country){
        repaintCountry(country, game.getOwnerOf(country).getColor());
    }
    
    public final void attackError(){
        popUpDialog(ERR_ATTACK);
        selCountry1 = null;
        selCountry2 = null;
        
    }
    
    public final void fortifyError(){
        popUpDialog(ERR_FORTIFY);
        selCountry1 = null;
        selCountry2 = null;
    }
    
    public final void tradingError(){
        popUpDialog(ERR_TRADE);
    }
    
    public final void tradingSuccessful(){
        popUpDialog(OK_TRADE);
    }
    
    private final void popUpDialog(final int type){
        if(type == ERR_ATTACK){
            JOptionPane.showMessageDialog(frame,"You must own the country where the attack start and have more that 1 army! \n Of course you can not attack yourself...", "RiskBaMi - Attack warning",JOptionPane.WARNING_MESSAGE);
        } else if(type == ERR_FORTIFY){
            JOptionPane.showMessageDialog(frame,"You must own both countries and left one army in the first territory!", "RiskBaMi - Fortify warning",JOptionPane.WARNING_MESSAGE);
        } else if(type == ERR_TRADE){
            JOptionPane.showMessageDialog(frame,"You choosen a not valid set of cards!", "RiskBaMi - Trade warning",JOptionPane.WARNING_MESSAGE);
        } else if(type == OK_TRADE){
            JOptionPane.showMessageDialog(frame,"Card selected are exchanged successfully", "RiskBaMi - Trade Successful",JOptionPane.INFORMATION_MESSAGE);
        } else if(type == GAME_FINISHED){
            JOptionPane.showMessageDialog(frame,"Congratulations, "+game.getCurrentPlayer()+" is the winner!!", "RiskBaMi - Congratulations",JOptionPane.INFORMATION_MESSAGE);
        }
    }
}
